/**
 * 配置管理系统前端脚本
 */

layui.define(['table', 'form', 'layer', 'element', 'upload'], function(exports) {
    var $ = layui.jquery,
        table = layui.table,
        form = layui.form,
        layer = layui.layer,
        element = layui.element,
        upload = layui.upload;

    var ConfigAdmin = {
        // API基础路径
        apiBase: '/admin/config',

        // 缓存的分组数据
        cachedGroups: [],

        // 初始化
        init: function() {
            // 初始渲染表单
            form.render();
            this.loadConfigGroups();
            this.bindEvents();
            this.loadSystemStatus();
            this.loadRecentChanges();
            this.startAutoRefresh();
        },

        // 加载配置分组
        loadConfigGroups: function() {
            var self = this;
            $.ajax({
                url: ConfigAdmin.apiBase + '/groups',
                method: 'GET',
                success: function(res) {
                    if (res.code === 200) {
                        // 缓存分组数据
                        self.cachedGroups = res.data;
                        self.renderConfigGroups(res.data);
                    } else {
                        layer.msg('加载配置分组失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.msg('加载配置分组失败', {icon: 2});
                }
            });
        },

        // 渲染配置分组树
        renderConfigGroups: function(groups) {
            var html = '';
            var overviewHtml = '<li class="layui-nav-item" data-page="overview"><a href="javascript:;"><i class="layui-icon layui-icon-home"></i> 系统概览</a></li>';

            groups.forEach(function(group) {
                html += '<li class="layui-nav-item" data-group="' + group.name + '" data-page="config">';
                html += '<a href="javascript:;"><i class="layui-icon ' + (group.icon || 'layui-icon-set') + '"></i> ' + group.display_name + '</a></li>';
            });

            // 添加其他页面
            html += '<li class="layui-nav-item" data-page="history"><a href="javascript:;"><i class="layui-icon layui-icon-log"></i> 配置历史</a></li>';
            html += '<li class="layui-nav-item" data-page="backup"><a href="javascript:;"><i class="layui-icon layui-icon-download-circle"></i> 备份管理</a></li>';

            $('#configGroupTree').html(overviewHtml + html);
            element.render('nav');

            // 默认显示概览页
            this.showPage('overview');
        },

        // 显示页面
        showPage: function(pageName, groupData) {
            var self = this;

            // 隐藏所有页面
            $('.config-page').hide();

            // 移除所有导航激活状态
            $('.layui-nav-item').removeClass('layui-this');

            // 显示对应页面
            switch(pageName) {
                case 'overview':
                    $('#overviewPage').show();
                    $('[data-page="overview"]').addClass('layui-this');
                    break;
                case 'config':
                    $('#configEditPage').show();
                    $('[data-group="' + groupData.name + '"]').addClass('layui-this');
                    self.loadConfigItems(groupData);
                    // 确保表单在显示时正确渲染
                    setTimeout(function() {
                        form.render();
                    }, 100);
                    break;
                case 'history':
                    $('#configHistoryPage').show();
                    $('[data-page="history"]').addClass('layui-this');
                    self.loadConfigHistory();
                    break;
                case 'backup':
                    $('#backupManagePage').show();
                    $('[data-page="backup"]').addClass('layui-this');
                    self.loadBackupList();
                    break;
            }

            ConfigAdmin.currentPage = pageName;
            ConfigAdmin.currentGroup = groupData;
        },

        // 加载配置项
        loadConfigItems: function(groupData) {
            var self = this;

            // 显示加载状态
            var loadingIndex = layer.load(2, {shade: 0.1});

            $.ajax({
                url: ConfigAdmin.apiBase + '/items',
                method: 'GET',
                data: { group_id: groupData.id },
                success: function(res) {
                    layer.close(loadingIndex);
                    if (res.code === 200) {
                        self.renderConfigItems(res.data);
                        self.renderCategoryFilter(res.data);
                        form.render();
                    } else {
                        layer.msg('加载配置项失败: ' + res.message, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loadingIndex);
                    layer.msg('加载配置项失败', {icon: 2});
                }
            });
        },

        // 渲染配置项
        renderConfigItems: function(items) {
            var self = this;
            var html = '';

            items.forEach(function(item) {
                html += self.renderConfigItem(item);
            });

            $('#configItemsContainer').html(html);
            self.originalConfigData = self.getCurrentFormData();
            ConfigAdmin.modifiedConfigs = {};
            ConfigAdmin.hasUnsavedChanges = false;
            self.updateSaveButtonStatus();
        },

        // 渲染单个配置项
        renderConfigItem: function(item) {
            var itemClass = 'config-item' + (item.is_sensitive ? ' config-item-sensitive' : '');
            var html = '<div class="' + itemClass + '" data-key="' + item.key_name + '" data-type="' + item.data_type + '">';
            html += '<div class="layui-form-item' + (item.is_sensitive ? ' config-item-sensitive' : '') + '">';
            // 构建标签的title属性
            var labelTitle = item.display_name;
            if (item.description) {
                labelTitle = item.description; // 将说明作为主要内容
            }

            html += '<label class="layui-form-label" title="' + (item.description || item.display_name) + '">';
            // 添加图标标识（显示在文字前面）
            if (item.is_sensitive) {
                html += '<i class="layui-icon layui-icon-password" title="敏感信息"></i> ';
            }
            if (item.is_reload_required) {
                html += '<i class="layui-icon layui-icon-refresh-1" title="需要重启生效"></i> ';
            }
            html += item.display_name;
            html += '</label>';
            html += '<div class="layui-input-block">';

            // 根据数据类型渲染不同的输入控件
            if (item.data_type === 'boolean') {
                var checked = item.current_value === 'true' || item.current_value === true;
                html += '<input type="checkbox" name="' + item.key_name + '" value="true"';
                if (checked) html += ' checked';
                if (item.is_readonly) html += ' disabled';
                html += ' lay-skin="switch" lay-text="启用|禁用">';
            } else if (item.data_type === 'secret' || (item.is_sensitive && item.key_name.includes('PASSWORD'))) {
                html += '<input type="password" name="' + item.key_name + '" value="' + (item.current_value || '') + '" class="layui-input"';
                if (item.placeholder) html += ' placeholder="' + item.placeholder + '"';
                if (item.is_readonly) html += ' readonly';
                html += '>';
                html += '<button type="button" class="layui-btn layui-btn-xs layui-btn-primary toggle-password">';
                html += '<i class="layui-icon layui-icon-eye"></i>';
                html += '</button>';
            } else if (item.data_type === 'json' || item.description && item.description.includes('JSON')) {
                html += '<textarea name="' + item.key_name + '" placeholder="' + (item.placeholder || '请输入JSON格式数据') + '" class="layui-textarea"';
                if (item.is_readonly) html += ' readonly';
                html += '>' + (item.current_value || '') + '</textarea>';
            } else if (item.data_type === 'integer') {
                html += '<input type="number" name="' + item.key_name + '" value="' + (item.current_value || '') + '" class="layui-input"';
                if (item.placeholder) html += ' placeholder="' + item.placeholder + '"';
                if (item.is_readonly) html += ' readonly';
                html += '>';
            } else {
                html += '<input type="text" name="' + item.key_name + '" value="' + (item.current_value || '') + '" class="layui-input"';
                if (item.placeholder) html += ' placeholder="' + item.placeholder + '"';
                if (item.is_readonly) html += ' readonly';
                html += '>';
            }

        
            html += '</div>';
            html += '</div>';
            html += '</div>';

            return html;
        },

        // 渲染分类筛选器
        renderCategoryFilter: function(items) {
            var categories = {};
            items.forEach(function(item) {
                if (item.category && !categories[item.category]) {
                    categories[item.category] = true;
                }
            });

            var html = '<option value="">全部分类</option>';
            for (var category in categories) {
                html += '<option value="' + category + '">' + category + '</option>';
            }

            $('#categoryFilter').html(html);
        },

        // 获取当前表单数据
        getCurrentFormData: function() {
            var data = {};
            $('.config-form input, .config-form textarea, .config-form select').each(function() {
                var $elem = $(this);
                var name = $elem.attr('name');
                if (!name) return;

                if ($elem.attr('type') === 'checkbox') {
                    data[name] = $elem.is(':checked') ? 'true' : 'false';
                } else if ($elem.attr('type') === 'radio') {
                    if ($elem.is(':checked')) {
                        data[name] = $elem.val();
                    }
                } else {
                    data[name] = $elem.val();
                }
            });
            return data;
        },

        // 获取变更项
        getChanges: function() {
            var currentData = this.getCurrentFormData();
            var changes = {};

            for (var key in currentData) {
                if (currentData[key] !== this.originalConfigData[key]) {
                    changes[key] = {
                        key: key,
                        value: currentData[key],
                        oldValue: this.originalConfigData[key]
                    };
                }
            }

            return changes;
        },

        // 检查是否有变更
        checkForChanges: function() {
            var changes = this.getChanges();
            ConfigAdmin.hasUnsavedChanges = Object.keys(changes).length > 0;

            // 更新配置项样式
            $('.config-item').removeClass('has-changes');
            for (var key in changes) {
                $('.config-item[data-key="' + key + '"]').addClass('has-changes');
            }

            this.updateSaveButtonStatus();
        },

        // 更新保存按钮状态
        updateSaveButtonStatus: function() {
            var $saveBtn = $('button[lay-filter="saveConfigBtn"]');
            if (ConfigAdmin.hasUnsavedChanges) {
                $saveBtn.addClass('layui-btn-danger').removeClass('layui-btn-normal');
            } else {
                $saveBtn.addClass('layui-btn-normal').removeClass('layui-btn-danger');
            }
        },

        // 加载系统状态
        loadSystemStatus: function() {
            var self = this;
            $.ajax({
                url: ConfigAdmin.apiBase + '/status',
                method: 'GET',
                success: function(res) {
                    if (res.code === 200) {
                        self.updateSystemStatus(res.data);
                    }
                }
            });
        },

        // 更新系统状态显示
        updateSystemStatus: function(status) {
            $('#totalConfigs').text(status.total_configs || '--');
            $('#pendingReload').text(status.reload_required_configs || '--');
            $('#sensitiveConfigs').text(status.sensitive_configs || '--');

            if (status.last_update) {
                $('#lastUpdateTime').text(new Date(status.last_update).toLocaleString());
            }

            $('#cacheStatus').text(status.cache_size || '--');

            // 更新系统状态指示器
            var $statusIndicator = $('#systemStatus .layui-icon');
            var $statusText = $('#statusText');

            if (status.system_status === 'healthy') {
                $statusIndicator.removeClass('layui-icon-close').addClass('layui-icon-ok-circle')
                    .css('color', '#5FB878');
                $statusText.text('运行正常');
            } else {
                $statusIndicator.removeClass('layui-icon-ok-circle').addClass('layui-icon-close')
                    .css('color', '#FF5722');
                $statusText.text('系统异常');
            }
        },

        // 加载最近变更
        loadRecentChanges: function() {
            var self = this;
            $.ajax({
                url: ConfigAdmin.apiBase + '/history/recent',
                method: 'GET',
                data: { hours: 24 },
                success: function(res) {
                    if (res.code === 200) {
                        self.renderRecentChanges(res.data);
                    }
                }
            });
        },

        // 渲染最近变更
        renderRecentChanges: function(changes) {
            var $tbody = $('#recentChangesBody');
            var $noData = $('#noRecentChanges');

            if (changes.length === 0) {
                $tbody.empty();
                $noData.show();
                return;
            }

            $noData.hide();
            var html = '';

            changes.forEach(function(change) {
                html += '<tr>';
                html += '<td>' + (change.display_name || change.config_key) + '</td>';
                html += '<td>';
                if (change.old_value !== null && change.new_value !== null) {
                    html += '<span class="change-value-old">' + change.old_value + '</span>';
                    html += ' → ';
                    html += '<span class="change-value-new">' + change.new_value + '</span>';
                } else if (change.change_type === 'reload') {
                    html += '<span class="change-type-tag change-type-reload">重载配置</span>';
                } else if (change.change_type === 'restart') {
                    html += '<span class="change-type-tag change-type-restart">重启服务</span>';
                }
                html += '</td>';
                html += '<td>' + (change.changed_by || 'system') + '</td>';
                html += '<td>' + (change.change_reason || '-') + '</td>';
                html += '<td>' + new Date(change.created_at).toLocaleString() + '</td>';
                html += '</tr>';
            });

            $tbody.html(html);
        },

        // 加载配置历史
        loadConfigHistory: function() {
            var self = this;
            var loadingIndex = layer.load(2, {shade: 0.1});

            $.ajax({
                url: ConfigAdmin.apiBase + '/history',
                method: 'GET',
                data: {
                    page: 1,
                    page_size: 20
                },
                success: function(res) {
                    layer.close(loadingIndex);
                    if (res.code === 200) {
                        self.renderHistoryTable(res.data);
                    } else {
                        layer.msg('加载历史记录失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loadingIndex);
                    layer.msg('加载历史记录失败', {icon: 2});
                }
            });
        },

        // 渲染历史记录表格
        renderHistoryTable: function(historyData) {
            var $tbody = $('#historyBody');
            var html = '';

            historyData.forEach(function(record) {
                html += '<tr>';
                html += '<td>' + new Date(record.created_at).toLocaleString() + '</td>';
                html += '<td>' + (record.display_name || record.config_key) + '</td>';
                html += '<td><span class="change-type-tag change-type-' + record.change_type + '">' + record.change_type + '</span></td>';
                html += '<td>' + (record.changed_by || 'system') + '</td>';
                html += '<td>' + (record.change_reason || '-') + '</td>';
                html += '<td>';
                if (record.old_value !== null && record.new_value !== null) {
                    html += '<div class="change-content">' + record.old_value + ' → ' + record.new_value + '</div>';
                } else {
                    html += '-';
                }
                html += '</td>';
                html += '<td>';
                html += '<button class="layui-btn layui-btn-xs layui-btn-primary" onclick="ConfigAdmin.viewHistoryDetail(\'' + record.id + '\')">详情</button>';
                html += '</td>';
                html += '</tr>';
            });

            $tbody.html(html);
        },

        // 查看历史详情
        viewHistoryDetail: function(historyId) {
            layer.open({
                type: 2,
                title: '变更详情',
                shadeClose: true,
                shade: 0.3,
                maxmin: true,
                area: ['800px', '600px'],
                content: ConfigAdmin.apiBase + '/history/' + historyId
            });
        },

        // 加载备份列表
        loadBackupList: function() {
            var self = this;
            var loadingIndex = layer.load(2, {shade: 0.1});

            $.ajax({
                url: ConfigAdmin.apiBase + '/backups',
                method: 'GET',
                data: {
                    page: 1,
                    page_size: 50
                },
                success: function(res) {
                    layer.close(loadingIndex);
                    if (res.code === 200) {
                        self.renderBackupTable(res.data);
                    } else {
                        layer.msg('加载备份列表失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loadingIndex);
                    layer.msg('加载备份列表失败', {icon: 2});
                }
            });
        },

        // 渲染备份表格
        renderBackupTable: function(backups) {
            var $tbody = $('#backupBody');
            var html = '';

            var self = this;
            backups.forEach(function(backup) {
                html += '<tr>';
                html += '<td>' + backup.backup_name + '</td>';
                html += '<td>' + new Date(backup.created_at).toLocaleString() + '</td>';
                html += '<td>' + (backup.created_by || 'system') + '</td>';
                html += '<td>' + ConfigAdmin.formatFileSize(backup.file_size) + '</td>';
                html += '<td>';
                if (backup.is_auto_backup) {
                    html += '<span class="backup-type-tag backup-type-auto">自动备份</span>';
                } else {
                    html += '<span class="backup-type-tag backup-type-manual">手动备份</span>';
                }
                html += '</td>';
                html += '<td>';
                html += '<button class="layui-btn layui-btn-xs layui-btn-normal" onclick="ConfigAdmin.viewBackupDetail(' + backup.id + ')">详情</button>';
                html += '<button class="layui-btn layui-btn-xs layui-btn-warm" onclick="ConfigAdmin.restoreBackup(' + backup.id + ')">恢复</button>';
                html += '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="ConfigAdmin.deleteBackup(' + backup.id + ')">删除</button>';
                html += '</td>';
                html += '</tr>';
            });

            $tbody.html(html);
        },

        // 格式化文件大小
        formatFileSize: function(bytes) {
            if (!bytes) return '-';

            var units = ['B', 'KB', 'MB', 'GB'];
            var size = bytes;
            var unitIndex = 0;

            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }

            return size.toFixed(2) + ' ' + units[unitIndex];
        },

        // 使用 Layui 表单数据保存配置
        saveConfigWithFormData: function(formData) {
            var self = this;
            var changes = this.getChanges();

            if (Object.keys(changes).length === 0) {
                layer.msg('没有配置变更', {icon: 3});
                return;
            }

            // 使用 Layui 表单数据更新变更记录
            for (var key in formData) {
                if (changes[key]) {
                    changes[key].value = formData[key];
                }
            }

            // 构建更新数据
            var updates = [];
            for (var key in changes) {
                updates.push({
                    key: key,
                    value: changes[key].value,
                    need_restart: false // 可以根据配置项属性设置
                });
            }

            // 显示确认对话框
            layer.confirm('确定要保存 ' + updates.length + ' 项配置更改吗？', function(index) {
                layer.close(index);

                var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

                $.ajax({
                    url: ConfigAdmin.apiBase + '/items/batch',
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        updates: updates,
                        change_reason: '通过管理界面修改'
                    }),
                    success: function(res) {
                        layer.close(loadingIndex);

                        if (res.code === 200) {
                            layer.msg('配置保存成功', {icon: 1});
                            self.originalConfigData = self.getCurrentFormData();
                            ConfigAdmin.hasUnsavedChanges = false;
                            self.updateSaveButtonStatus();
                            self.loadSystemStatus();

                            // 检查是否需要重启
                            var needRestart = updates.some(function(update) {
                                // 这里可以根据配置属性判断是否需要重启
                                return false;
                            });

                            if (needRestart) {
                                layer.confirm('配置已保存，但某些更改需要重启服务才能生效。是否立即重启？', function(index) {
                                    layer.close(index);
                                    self.restartService();
                                });
                            }

                            // 移除变更样式
                            $('.config-item').removeClass('has-changes');

                        } else {
                            layer.msg('配置保存失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(loadingIndex);
                        layer.msg('网络请求失败', {icon: 2});
                    }
                });
            });
        },

        // 保存配置
        saveConfig: function() {
            var self = this;
            var changes = this.getChanges();

            if (Object.keys(changes).length === 0) {
                layer.msg('没有配置变更', {icon: 3});
                return;
            }

            // 构建更新数据
            var updates = [];
            for (var key in changes) {
                updates.push({
                    key: key,
                    value: changes[key].value,
                    need_restart: false // 可以根据配置项属性设置
                });
            }

            // 显示确认对话框
            layer.confirm('确定要保存 ' + updates.length + ' 项配置更改吗？', function(index) {
                layer.close(index);

                var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

                $.ajax({
                    url: ConfigAdmin.apiBase + '/items/batch',
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        updates: updates,
                        change_reason: '前端界面配置更新'
                    }),
                    success: function(res) {
                        layer.close(loadingIndex);

                        if (res.code === 200) {
                            layer.msg('配置保存成功', {icon: 1});
                            self.originalConfigData = self.getCurrentFormData();
                            ConfigAdmin.hasUnsavedChanges = false;
                            self.updateSaveButtonStatus();
                            self.loadSystemStatus();

                            // 检查是否需要重启
                            var needRestart = updates.some(function(update) {
                                // 这里可以根据配置属性判断是否需要重启
                                return false;
                            });

                            if (needRestart) {
                                layer.confirm('配置已保存，但某些更改需要重启服务才能生效。是否立即重启？', function(index) {
                                    layer.close(index);
                                    self.restartService();
                                });
                            }

                            // 移除变更样式
                            $('.config-item').removeClass('has-changes');

                        } else {
                            layer.msg('配置保存失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(loadingIndex);
                        layer.msg('网络请求失败', {icon: 2});
                    }
                });
            });
        },

        // 重载配置
        reloadConfig: function() {
            var self = this;

            layer.confirm('确定要重载配置吗？', function(index) {
                layer.close(index);

                var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

                $.ajax({
                    url: ConfigAdmin.apiBase + '/reload',
                    method: 'POST',
                    success: function(res) {
                        layer.close(loadingIndex);

                        if (res.code === 200) {
                            layer.msg('配置重载成功', {icon: 1});
                            if (ConfigAdmin.currentPage === 'config' && ConfigAdmin.currentGroup) {
                                self.loadConfigItems(ConfigAdmin.currentGroup);
                            }
                            self.loadSystemStatus();
                        } else {
                            layer.msg('配置重载失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(loadingIndex);
                        layer.msg('配置重载失败', {icon: 2});
                    }
                });
            });
        },

        // 重启服务
        restartService: function() {
            layer.confirm('确定要重启服务吗？这将中断当前所有连接。', function(index) {
                layer.close(index);

                var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

                $.ajax({
                    url: ConfigAdmin.apiBase + '/restart',
                    method: 'POST',
                    success: function(res) {
                        layer.close(loadingIndex);

                        if (res.code === 200) {
                            layer.msg('服务重启命令已发送，页面将在3秒后刷新', {icon: 1});
                            setTimeout(function() {
                                location.reload();
                            }, 3000);
                        } else {
                            layer.msg('服务重启失败: ' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.close(loadingIndex);
                        layer.msg('服务重启失败', {icon: 2});
                    }
                });
            });
        },

        // 创建备份
        createBackup: function() {
            var self = this;

            layer.open({
                type: 1,
                title: '创建配置备份',
                content: $('#createBackupDialog'),
                area: ['500px', '300px'],
                btn: ['创建', '取消'],
                yes: function(index) {
                    var backupName = $('input[name="backupName"]').val();
                    var backupDescription = $('textarea[name="backupDescription"]').val();

                    if (!backupName) {
                        layer.msg('请输入备份名称', {icon: 2});
                        return false;
                    }

                    var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

                    $.ajax({
                        url: ConfigAdmin.apiBase + '/backups',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            backup_name: backupName,
                            backup_description: backupDescription
                        }),
                        success: function(res) {
                            layer.close(loadingIndex);
                            layer.close(index);

                            if (res.code === 200) {
                                layer.msg('备份创建成功', {icon: 1});
                                if (ConfigAdmin.currentPage === 'backup') {
                                    self.loadBackupList();
                                }
                            } else {
                                layer.msg('备份创建失败: ' + res.message, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.close(loadingIndex);
                            layer.msg('备份创建失败', {icon: 2});
                        }
                    });
                }
            });
        },

        // 搜索配置项
        searchConfigItems: function() {
            var keyword = $('#configSearchInput').val().toLowerCase();
            var category = $('#categoryFilter').val();

            $('.config-item').each(function() {
                var $item = $(this);
                var key = $item.data('key').toLowerCase();
                var show = true;

                if (keyword && key.indexOf(keyword) === -1) {
                    show = false;
                }

                if (category && $item.find('.config-category').text() !== category) {
                    show = false;
                }

                $item.toggle(show);
            });
        },

        // 重置搜索
        resetSearch: function() {
            $('#configSearchInput').val('');
            $('#categoryFilter').val('');
            $('.config-item').show();
            form.render('select');
        },

        // 导出配置
        exportConfigs: function() {
            var loadingIndex = layer.load(2, {shade: [0.3, '#000']});

            window.open(ConfigAdmin.apiBase + '/export?format=json', '_blank');

            setTimeout(function() {
                layer.close(loadingIndex);
            }, 1000);
        },

        // 启动自动刷新
        startAutoRefresh: function() {
            var self = this;

            // 每30秒刷新系统状态
            setInterval(function() {
                self.loadSystemStatus();
            }, 30000);

            // 每2分钟刷新最近变更
            setInterval(function() {
                if (ConfigAdmin.currentPage === 'overview') {
                    self.loadRecentChanges();
                }
            }, 120000);
        },

        // 绑定事件
        bindEvents: function() {
            var self = this;

            // 导航菜单点击事件
            $(document).on('click', '.layui-nav-item', function() {
                var $item = $(this);
                var page = $item.data('page');
                var group = $item.data('group');

                if (page === 'config' && group) {
                    // 从缓存数据中查找对应的分组信息
                    var groupName = $item.data('group');
                    var groupData = self.cachedGroups.find(function(g) {
                        return g.name === groupName;
                    });

                    if (groupData) {
                        self.showPage('config', groupData);
                    } else {
                        layer.msg('分组数据未找到: ' + groupName, {icon: 2});
                    }
                } else {
                    self.showPage(page);
                }
            });

            // 搜索和筛选
            $('#searchBtn').on('click', function() {
                self.searchConfigItems();
            });

            $('#resetSearchBtn').on('click', function() {
                self.resetSearch();
            });

            $('#configSearchInput').on('keyup', function(e) {
                if (e.keyCode === 13) {
                    self.searchConfigItems();
                }
            });

            // 表单提交
            form.on('submit(saveConfigBtn)', function(data) {
                self.saveConfigWithFormData(data.field);
                return false;
            });

            // 表单变化监听
            $(document).on('change', '.config-form input, .config-form textarea, .config-form select', function() {
                self.checkForChanges();
            });

            // 密码显示切换
            $(document).on('click', '.toggle-password', function() {
                var $input = $(this).siblings('input');
                var $icon = $(this).find('i');

                if ($input.attr('type') === 'password') {
                    $input.attr('type', 'text');
                    $icon.removeClass('layui-icon-eye').addClass('layui-icon-face-cry');
                } else {
                    $input.attr('type', 'password');
                    $icon.removeClass('layui-icon-face-cry').addClass('layui-icon-eye');
                }
            });

            // 顶部按钮事件
            $('#reloadAllConfig').on('click', function() {
                self.reloadConfig();
            });

            $('#restartService').on('click', function() {
                self.restartService();
            });

            $('#createBackupBtn').on('click', function() {
                self.createBackup();
            });

            $('#exportConfigsBtn').on('click', function() {
                self.exportConfigs();
            });

            $('#viewHistoryBtn').on('click', function() {
                self.showPage('history');
            });

            $('#viewAllHistoryBtn').on('click', function() {
                self.showPage('history');
            });

            $('#refreshHistoryBtn').on('click', function() {
                self.loadRecentChanges();
            });

            // 配置页面按钮
            $('#resetConfigBtn').on('click', function() {
                layer.confirm('确定要重置所有更改吗？', function(index) {
                    layer.close(index);
                    if (ConfigAdmin.currentGroup) {
                        self.loadConfigItems(ConfigAdmin.currentGroup);
                    }
                });
            });

            $('#validateAllBtn').on('click', function() {
                self.validateAllConfigs();
            });

            $('#exportGroupBtn').on('click', function() {
                self.exportConfigs();
            });

            // 历史页面按钮
            $('#searchHistoryBtn').on('click', function() {
                self.searchHistory();
            });

            // 备份页面按钮
            $('#createNewBackupBtn').on('click', function() {
                self.createBackup();
            });

            $('#cleanupOldBackupsBtn').on('click', function() {
                self.cleanupOldBackups();
            });
        },

        // 验证所有配置
        validateAllConfigs: function() {
            var self = this;
            var currentData = this.getCurrentFormData();
            var hasErrors = false;

            $('.config-item').removeClass('has-error');
            $('.config-validation').remove();

            for (var key in currentData) {
                (function(k) {
                    $.ajax({
                        url: ConfigAdmin.apiBase + '/validate',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            key: k,
                            value: currentData[k]
                        }),
                        success: function(res) {
                            if (res.code === 200) {
                                var validation = res.data;
                                if (!validation.is_valid) {
                                    hasErrors = true;
                                    var $item = $('.config-item[data-key="' + k + '"]');
                                    $item.addClass('has-error');

                                    var $validation = $('<div class="config-validation">' +
                                        '<i class="layui-icon layui-icon-close-fill"></i>' +
                                        '<span class="error-message">' + validation.error_message + '</span>' +
                                        '</div>');
                                    $item.find('.layui-input-block').append($validation);
                                }
                            }
                        }
                    });
                })(key);
            }

            setTimeout(function() {
                if (hasErrors) {
                    layer.msg('配置验证失败，请检查红色标记的配置项', {icon: 2});
                } else {
                    layer.msg('所有配置验证通过', {icon: 1});
                }
            }, 2000);
        },

        // 搜索历史记录
        searchHistory: function() {
            var self = this;
            var configKey = $('#historyConfigKey').val();
            var changeType = $('#historyChangeType').val();

            var loadingIndex = layer.load(2, {shade: 0.1});

            $.ajax({
                url: ConfigAdmin.apiBase + '/history',
                method: 'GET',
                data: {
                    config_key: configKey || undefined,
                    change_type: changeType || undefined,
                    page: 1,
                    page_size: 20
                },
                success: function(res) {
                    layer.close(loadingIndex);
                    if (res.code === 200) {
                        self.renderHistoryTable(res.data);
                    } else {
                        layer.msg('搜索历史记录失败', {icon: 2});
                    }
                },
                error: function() {
                    layer.close(loadingIndex);
                    layer.msg('搜索历史记录失败', {icon: 2});
                }
            });
        },

        // 清理旧备份
        cleanupOldBackups: function() {
            layer.confirm('确定要清理30天前的自动备份吗？', function(index) {
                layer.close(index);

                // 这里应该调用清理API
                layer.msg('备份清理功能开发中', {icon: 3});
            });
        }
    };

    // 初始化
    $(document).ready(function() {
        ConfigAdmin.init();
    });

    // 导出到全局
    window.ConfigAdmin = ConfigAdmin;

    exports('configAdmin', ConfigAdmin);
});